package cn.wizzer.app.web.modules.controllers.platform.bus;

import cn.wizzer.app.bus.modules.models.YJbxx;
import cn.wizzer.app.bus.modules.models.YJbxxLcxx;
import cn.wizzer.app.bus.modules.models.YJbxxLzxx;
import cn.wizzer.app.bus.modules.services.YJbxxLcxxService;
import cn.wizzer.app.bus.modules.services.YJbxxLzxxService;
import cn.wizzer.app.bus.modules.services.YJbxxService;
import cn.wizzer.app.sys.modules.services.SysDictService;
import cn.wizzer.app.sys.modules.services.SysUnitService;
import cn.wizzer.app.sys.modules.services.SysUserService;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.DateUtil;
import cn.wizzer.app.web.commons.utils.ShiroUtil;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.framework.base.Result;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;

import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 样品移交  虞秀斌  2019-11
 */
@IocBean
@At("/platform/bus/rwgl")
public class RwglController {
    private static final Log log = Logs.get();
    @Inject
    private YJbxxService yjbxxService;
    @Inject
    private YJbxxLcxxService yjbxxlcxxservice;
    @Inject
    private SysDictService sysDictService;
    @Inject
    private SysUserService sysUserService;
    @Inject
    private SysUnitService sysUnitService;
    @Inject
    private ShiroUtil shiroUtil;
    @Inject
    private YJbxxLzxxService yjbxxlzxxservice;
    @At("/?")
    @Ok("beetl:/platform/bus/rwgl/list.html")
    @RequiresPermissions(value = {"bus.rwgl.rwfp","bus.rwgl.rwrl","bus.rwgl.rwch"},logical = Logical.OR)
    public void index(String operation,HttpServletRequest req) {
        req.setAttribute("jylxMap", JSONObject.fromObject(sysDictService.getCodeMap("jylx")));
        String lczt="";
        if(operation.equals("rwfp")){
            lczt="1,3";
        }
        else if(operation.equals("rwrl")){
            lczt="1,3";
        }
        else if(operation.equals("rwch")){
            lczt="2";
        }
        req.setAttribute("lczt",lczt);
        req.setAttribute("operation",operation);
        req.setAttribute("userId",shiroUtil.getPrincipalProperty("id").toString());
        req.setAttribute("username",shiroUtil.getPrincipalProperty("username").toString());
        req.setAttribute("lcztMap", JSONObject.fromObject(sysDictService.getCodeMap("lczt")));
        req.setAttribute("lzztMap", JSONObject.fromObject(sysDictService.getCodeMap("lzzt")));



    }

    @At
    @Ok("json:{locked:'password|salt',ignoreNull:false}")
    @RequiresPermissions("bus.rwgl")
    public Object data(@Param("searchKeyword") String searchKeyword,@Param("lczt") String lczt, @Param("pageNumber") int pageNumber,
                       @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        try {
            String sql ="SELECT jbxx.id,jbxx.lzzt,jbxx.status,jbxx.lczt, jbxx.ypbh,jbxx.bgbh, jbxx.ypmc, jbxx.jylx, jbxx.jyks, jbxx.wtdw, jbxx.ggxh, jbxx.scrqpc, jbxx.sb, jbxx.wcqx, '' AS sysj, jbxx.jyfy,FROM_UNIXTIME(jbxx.opAt) as tjsj,jl.nextSpr " +
                    " FROM y_jbxx jbxx LEFT JOIN y_jbxx_lcxx jl on jl.jbxxId=jbxx.id and jl.lczt=2 and jl.delFlag=0 where 1=1 and jbxx.lczt in("+lczt+") and jbxx.lzzt>0 and jbxx.delflag = 0 ";
            if (Strings.isNotBlank(searchKeyword)) {
                sql+= " and (jbxx.ypbh like '%"+searchKeyword+"%' or  jbxx.ypmc like '%"+searchKeyword+"%')";
            }
            String unitid = shiroUtil.getPrincipalProperty("unitid").toString();
            List list = sysUnitService.list(Sqls.create("select id from sys_unit where id = '"+unitid+"' and sfjybm = 1 and delflag = 0 "));
            if(list.size()>0 ){
                sql+= " and jbxx.jyksbh like '%"+unitid+"%' ";
            }else{
                //sql+=StringUtil.dataScopeFilter("");
            }
            if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
                if ("ascending".equalsIgnoreCase(pageOrderBy)) {
                    sql+= " order by jbxx."+pageOrderName+" asc,jbxx.opAt desc ";
                } else {
                    sql+= " order by jbxx."+pageOrderName+" desc,jbxx.opAt desc ";
                }
            }else{
                sql+= " order by jbxx.opAt desc ";
            }
            return Result.success().addData(yjbxxService.listPage(pageNumber,pageSize, Sqls.create(sql)));
        } catch (Exception e) {
            return Result.error();
        }
    }


    @At("/tofp/?")
    @Ok("json")
    @RequiresPermissions("bus.rwgl.tofp")
    public Object tofp(String id) {
        YJbxx obj = yjbxxService.fetch(id);
        Map map = new HashMap();
        map.put("userOptions",JSONArray.fromObject(sysUserService.getUserS(obj.getJyksbh())));
        String users = "";
        List<YJbxxLzxx> lzList = yjbxxlzxxservice.listEntity(Sqls.create("select * from y_jbxx_lzxx where jbxxId ='"+id+"' and lzzt =1 and status = '1' and delFlag=0  order by opAt asc "));
        if(lzList.size()>0){
            users =lzList.stream().map(t->t.getNextsprIds()).distinct().collect(Collectors.joining(","));
        }
        map.put("users",users);
        try {
            return Result.success().addData(map);
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At
    @Ok("json")
    @RequiresPermissions("bus.rwgl")
    @SLog(tag = "任务分配，认领，撤回", msg = "样品:${args[0].ypbh}")
    public Object rwglDo(@Param("..") YJbxxLcxx obj,@Param("operation") String operation) {
        try {
            YJbxx jbxx = yjbxxService.fetch(obj.getJbxxId());
            jbxx.setLczt(obj.getLczt());
            if(operation.equals("rwfp")){
                obj.setSpyj("任务分配");
            }else if(operation.equals("rwrl")){
                obj.setSpyj("任务认领");
            }else if(operation.equals("rwch")){
                obj.setSpyj("任务撤回");
            }
            Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                public void run() {
                    yjbxxlcxxservice.execute(Sqls.create("update y_jbxx_lcxx set delflag=1 where lczt>="+jbxx.getLczt()+" and jbxxid='"+jbxx.getId()+"'"));
                    yjbxxlcxxservice.insert(obj);
                    yjbxxService.update(jbxx);
                    yjbxxlcxxservice.clearCache();
                }
            });
            return Result.success("操作成功！");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }
}
